package jmu.tools.file.sync.util.action ;


import java.io.File ;

import jmu.tools.file.sync.util.AbstractAction ;
import jmu.tools.file.sync.util.LogManager ;
import jmu.tools.file.sync.util.SyncResult ;
import jmu.tools.file.sync.util.ThreadManager ;
import jmu.tools.file.sync.util.LogManager.Type ;


/**
 * Scanning action implementation
 * 
 * @author vkushnir
 */
public class ScanningAction extends AbstractAction
{
    private ThreadManager output ;

    /**
     * Create new scanning action
     * 
     * @param log
     * @param result
     * @param output
     */
    public ScanningAction ( final LogManager log, final SyncResult result, final ThreadManager output )
    {
        super ( log, result ) ;
        setOutput ( output ) ;
    }

    /**
     * Get output manager
     * 
     * @return thread manager
     */
    public ThreadManager getOutput ()
    {
        return output ;
    }

    @Override
    public void handle ( final ThreadManager input, final File source, final File destination )
    {
        // handle each child
        Type type = Type.DIR ;
        StringBuilder b = new StringBuilder ( source.getAbsolutePath () ) ;
        try
        {
            File newDest = null ;
            for ( final File f : source.listFiles () )
            {
                newDest = new File ( destination, f.getName () ) ;
                if ( f.isDirectory () )
                {
                    input.add ( f, newDest ) ;
                }
                else
                {
                    getOutput ().add ( f, newDest ) ;
                    getResult ().scan ( f ) ;
                }
            }
        }
        catch ( Exception e )
        {
            error ( "scan directory failed: " + e.getLocalizedMessage () ) ;
            b.append ( SEPARATOR ).append ( destination.getAbsolutePath () ) ;
            type = Type.DIR_FAIL ;

        }
        finally
        {
            b.append ( NEWLINE ) ;
            getLog ().log ( type, b.toString () ) ;
        }
    }

    /**
     * Set output manager
     * 
     * @param output
     */
    public void setOutput ( final ThreadManager output )
    {
        if ( null == output )
        {
            throw new IllegalArgumentException ( "output manager can't be null" ) ;
        }
        this.output = output ;
    }
}
